<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>新增采购订单</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //以销定采
        var purchaseBaseOnSales = '<%=@purchaseBaseOnSales%>';

        //是否临时保存
        var temporary = new Ext.form.Hidden({
          name: 'temporary',
          value: 0
        });
        
        //备注
        var desc = new Ext.form.TextField({
          fieldLabel: '备注',
          name: 'description',
          anchor: '97%'
        });
        
        //供应商相关combobox
        var vendorTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{name}', '</div></tpl>');
        vendorTemplate.compile();
        var vendorStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/vendor/getAllVendors?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'name'
            }, {
              name: 'phone'
            }, {
              name: 'linkman'
            }])
        });
        vendorStore.load();
        
        //供应商
        var vendor = new Ext.form.ComboBox({
          store: vendorStore,
          fieldLabel: '供应商',
          allowBlank: false,
          blankText: "供应商必须选择",
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'vendor_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '95%',
          //pageSize: 10,
          //hideTrigger: false,
          readOnly:false,
          tpl: vendorTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction: 'all',
          editable:false,
          selectOnFocus:true
        });

        vendor.on('select', function(combo, record, index) {
          linkman.setValue(record.get('linkman'));
          phone.setValue(record.get('phone'));
        });
        
        //要求发货时间
        var actionDate = new Ext.form.DateField({
          fieldLabel: '到货日期',
          allowBlank: false,
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          blankText: "到货日期必须选择",
          anchor: '95%',
          emptyText: '到货日期...'
        });
        //合同号
        var contractNumber = new Ext.form.TextField({
          fieldLabel: '合同编号',
          allowBlank: true,
          name: 'contract_number',
          anchor: '95%'
        });

        //联系人
        var linkman = new Ext.form.TextField({
          fieldLabel: '联系人',
          name: 'linkman',
          anchor: '95%',
          allowBlank: false
        });
        
        //联系电话
        var phone = new Ext.form.TextField({
          fieldLabel: '联系电话',
          name: 'phone',
          anchor: '95%',
          allowBlank: false
        });

        //税率
        var taxRate = new Ext.form.NumberField({
          fieldLabel: '税率(%)',
          name:"tax_rate",
          allowBlank: false,
          allowDecimals: true,
          allowNegative: false,
          maxValue: 100,
          value: 17,
          anchor: '95%'
        });

        var deliveryAddress = new Ext.form.TextField({
          fieldLabel: '送货地址',
          allowBlank: false,
          name: 'delivery_address',
          value: '<%=@purchasingShippingAddress%>',
          anchor: '95%'
        });

        //总金额
        var sumAmount = new Ext.form.NumberField({
          fieldLabel: '总金额',
          name:"amount",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          allowNegative: false,
          anchor: '90%'
        });

        //总进项税
        var sumVATAmount = new Ext.form.NumberField({
          fieldLabel: '总税额',
          name:"value_added_tax_amount",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          allowNegative: false,
          anchor: '90%'
        });
        
        //含税总金额
        var sumTaxAmount = new Ext.form.NumberField({
          fieldLabel: '含税总金额',
          name:"tax_amount",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          allowNegative: false,
          anchor: '90%'
        });
        //--------------------------------------------------------------------------
        
        //销售订单单号combobox
        var saleOrderNumberTemplate = new Ext.XTemplate('<tpl for="."><div  class="search-item">', '{order_number}', '</div></tpl>');
        saleOrderNumberTemplate.compile();
        var saleOrderNumberStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/sale_order/getSaleOrersForPurchase"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'order_number'
            }])
        });
        //销售订单CBB
        var saleOrderNumberCBB = new Ext.form.ComboBox({
          store: saleOrderNumberStore,
          fieldLabel: '销售订单单号',
          allowBlank: false,
          blankText: "销售订单必须选择",
          emptyText: '请选择...',
          displayField: 'order_number',
          hideTrigger:false,
          triggerAction:"all",
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '100%',
          pageSize: 10,
          tpl: saleOrderNumberTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });
        
        saleOrderNumberCBB.on('select', function(combo, record, index) {
          var purchaseOrderItemRecord = purchaseOrderDetailSM.getSelected();
          if (!purchaseOrderItemRecord) {
            return false;
          }
          purchaseOrderItemRecord.reject();
          purchaseOrderItemRecord.set('sale_order_id',record.get('id'));
          purchaseOrderItemRecord.set('sale_order_number',record.get('order_number'));
        });

        //产品列表
        //var productTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">{name}</div>', '</tpl>');
        var productTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">','<div style="float:left; width:220px">{name}</div><div style="float:left; width:110px">{number}</div>{is_suit}','</div></tpl>');
        
        productTemplate.compile();
        var productStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/sale_order/getProductsOfSaleOrder"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'product_id',
              mapping:'id'
            }, {
              name: 'name'
            }, {
              name: 'spec'
            }, {
              name: 'unit'
            }, {
              name: 'unit_price'
            }, {
              name: 'quantity'
            }, {
              name: 'description'
            }, {
              name: 'is_suit',
              mapping:'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        //产品
        var productCBB = new Ext.form.ComboBox({
          store: productStore,
          allowBlank: false,
          blankText: "产品必须选择",
          emptyText: '请选择...',
          displayField: 'name',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '100%',
          pageSize: 10,
          tpl: productTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });

        productCBB.on('select', function(combo, record, index) {
          var purchaseOrderItemRecord = purchaseOrderDetailSM.getSelected();
          if (!purchaseOrderItemRecord) {
            return false;
          }
          //打开了，重复的记录不允许存在(暂时去掉)，也就是说重复的记录也可以存在。
          if (isDuplicateBySaleOrderProduct(purchaseOrderDetailDS,purchaseOrderItemRecord.get('sale_order_id'),record.get('product_id'))){
            //删除当前记录
            purchaseOrderDetailDS.remove(purchaseOrderItemRecord);
          }else{
            purchaseOrderItemRecord.set('number',record.get('number'));
            purchaseOrderItemRecord.set('spec',record.get('spec'));
            purchaseOrderItemRecord.set('unit',record.get('unit'));
            purchaseOrderItemRecord.set('unit_price',record.get('unit_price'));
            purchaseOrderItemRecord.set('amount',record.get('unit_price'));
            purchaseOrderItemRecord.set('quantity',record.get('quantity'));
            purchaseOrderItemRecord.set('product_id',record.get('product_id'));
            //判断套装
            purchaseOrderItemRecord.set('is_suit',record.get('is_suit'));
            
            /*Ext.Ajax.request({
              url : '/stock/getProductStockQuantity',
              success : function (result, request) {
                purchaseOrderItemRecord.set('stock_quantity_1',result.responseText.split("|")[0]);
                purchaseOrderItemRecord.set('stock_quantity_2',result.responseText.split("|")[1]);
                if (purchaseOrderItemRecord.get('sale_order_id') != 0){
                  //限制即时最大采购数
                  Ext.Ajax.request({
                    url : '/purchase_order/getProductQuantityForPurchase',
                    success : function (result, request) {
                      purchaseOrderItemRecord.set('quantity',result.responseText);
                      purchaseOrderItemRecord.set('balance_quantity',result.responseText);
                      getSumAmount();
                    },
                    failure : function (result, request){
                      Ext.MessageBox.show({
                        title: '消息',
                        msg: "通讯失败，请从新操作1",
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.WARNING
                      });
                    },
                    method : 'GET',
                    params : {
                      sale_order_id : purchaseOrderItemRecord.get('sale_order_id'),
                      product_id : record.get('product_id')
                    }
                  });
                } else{
                  purchaseOrderItemRecord.set('balance_quantity',1000000);
                }
              },
              failure : function (result, request){
                Ext.MessageBox.show({
                  title: '消息',
                  msg: "通讯失败，请从新操作2",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.WARNING
                });
              },
              method : 'GET',
              params : {
                id : record.get('product_id')
              }
            });
            */
          }
        });

        productCBB.on('focus', function(combo, record, index) {
          var records = purchaseOrderDetailGrid.getSelectionModel().getSelections();
          productStore.baseParams.id = records[0].get('sale_order_id');
          productStore.baseParams.start=0;
          productStore.baseParams.limit=10;
          productStore.load();          
        });
        
        //采购订单列表Grid Store
        var purchaseOrderDetailDS = new Ext.data.Store({
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'sale_order_id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'description'
            }, {
              name: 'unit_price',
              type: 'float'
            }, {
              name: 'tax_price',
              type: 'float'
            }, {
              name: 'tax_amount',
              type: 'float'
            }, {
              name: 'value_added_tax',
              type: 'float'
            }, {
              name: 'quantity',
              type: 'int'
            },{
              name: 'product_id'
            },{
              name: 'amount',
              type: 'float'
            },{
              name: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        //生成产品Grid的CM
        var purchaseOrderDetailSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        //var purchaseOrderDetailSM = new Ext.grid.RowSelectionModel({singleSelect:true});
        var purchaseOrderDetailCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),purchaseOrderDetailSM,{
              header: '销售订单Id',
              dataIndex: 'sale_order_id',
              hidden:true,
              width: 30
            },{
              header: '销售订单',
              dataIndex: 'sale_order_number',
              editor: saleOrderNumberCBB,
              width: 195
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              editor: productCBB,
              width: 390
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden:true
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 90
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 50
            },{
              header: '数量',
              dataIndex: 'quantity',
              editor: new Ext.form.NumberField({
                allowBlank: false,
                allowDecimals: false,
                allowNegative: false
              }),
              align: 'right',
              width: 50
            },{
              header: '工库',
              dataIndex: 'stock_quantity_1',
              align: 'right',
              renderer: stockQuantityRender,
              hidden:true,
              width: 50
            },{
              header: '大库',
              dataIndex: 'stock_quantity_2',
              align: 'right',
              renderer: stockQuantityRender,
              hidden:true,
              width: 50
            },{
              header: '单价',
              dataIndex: 'unit_price',              
              renderer: Ext.util.Format.numberRenderer('0,000.0000000000'),
              align: 'right',
              width: 75
            },{
              header: '金额',
              dataIndex: 'amount',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 70
            },{
              header: '含税单价',
              dataIndex: 'tax_price',
              editor: new Ext.form.NumberField({
                allowBlank: false,
                allowDecimals: true,
                allowNegative: false,
                decimalPrecision: 2
              }),
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 80
            },{
              header: '进项税',
              dataIndex: 'value_added_tax',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 70
            },{
              header: '含税金额',
              dataIndex: 'tax_amount',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 80
            },{
              header: '套装',
              dataIndex: 'is_suit',
              width: 50
            },{
              header: '备注',
              dataIndex: 'description',
              width: 90,
              editor:new Ext.form.TextField({
                name: 'description',
                anchor: '90%'
              })
            },{
              header: '销售采购差',
              dataIndex: 'balance_quantity',
              width: 90,
              hidden: true
            }
          ]});

        //生成要订单的产品的Grid
        var purchaseOrderDetailGrid = new Ext.grid.EditorGridPanel({
          store: purchaseOrderDetailDS,
          cm: purchaseOrderDetailCM,
          sm: purchaseOrderDetailSM,
          width: 1230,
          height: 315,
          //title: '进货品种列表',
          clicksToEdit: 1,//这里应该是单击就可以修改的意思。因为默认是要双击的。
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                // access the Record constructor through the grid's store
                var Product = purchaseOrderDetailGrid.getStore().recordType;
                var record = null;
                if (purchaseBaseOnSales ==='否'){
                  record = new Product({
                    sale_order_id:0,
                    sale_order_number: '无销售订单关联'
                  });
                  //saleOrderNumberCBB.setDisabled(true);
                }else{
                  record = new Product({
                    sale_order_number: '请选择销售订单'
                  });
                }
                purchaseOrderDetailGrid.stopEditing();
                purchaseOrderDetailDS.insert(0, record);
                purchaseOrderDetailGrid.startEditing(0, 0);                
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var record = purchaseOrderDetailSM.getSelected();
                if (!record) {
                  return false;
                }
                getSumAmount();
                purchaseOrderDetailDS.remove(record);
              }
            }]
        });

        purchaseOrderDetailGrid.on('rowdblclick', function(gridPanel, rowIndex, e){
          var productId = purchaseOrderDetailDS.getAt(rowIndex).get('product_id');
          var tt = new Ext.ToolTip({
            target: e.target,
            width: 200,
            autoLoad: {url: 'stock/simpleStockForToolTipByProductId?product_id='+productId+"t="+(new Date()).getTime()},
            dismissDelay: 20000 // auto hide after 15 seconds
          });
        });

        
        //提交按钮
        var submitButton = new Ext.Button({
          text: '提交',
          tooltip: '提交采购订单。',
          iconCls: 'icon-save',
          handler: function(){
            if (purchaseOrderFormPanel.form.isValid()) {
              
              var productsJsonStr = gridStoreToJson(purchaseOrderDetailDS,rejectKeyArray);
              if (purchaseOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }

              //检查一下，有没有销售，产品，价格三元素完全相同的记录存在。如果存在就要检查
              if (isDuplicateForPurchase(purchaseOrderDetailDS)){
                Ext.MessageBox.show({
                  title: '消息',
                  msg: "有销售，产品，价格三者完全相同的记录存在，请检查！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = purchaseOrderFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/purchase_order/create',
                success : function (result, request) {
                  if (Ext.util.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "新增采购订单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.util.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  newPurchaseOrderWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作3",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newPurchaseOrderWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //临时保存按钮
        var tempSaveButton = new Ext.Button({
          text: '暂存',
          tooltip: '暂时保存采购订单。',
          iconCls: 'temp-save',
          handler: function(){
            if (vendor.getRawValue() === vendor.getValue()){
              vendor.reset();
            }
            
            //首先把临时变量设置为1
            temporary.setValue(1);

            if (purchaseOrderFormPanel.form.isValid()){

              var productsJsonStr = gridStoreToJson(purchaseOrderDetailDS,rejectKeyArray);
              if (purchaseOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              
              //没有添加产品，则提示
              if (purchaseOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }

              //检查一下，有没有销售，产品，价格三元素完全相同的记录存在。如果存在就要检查
              if (isDuplicateForPurchase(purchaseOrderDetailDS)){
                Ext.MessageBox.show({
                  title: '消息',
                  msg: "有销售，产品，价格三者完全相同的记录存在，请检查！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              
              this.disable();
              var allJsonStr = purchaseOrderFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

              Ext.Ajax.request({
                url : '/purchase_order/create',
                success : function (result, request) {
                  if (Ext.util.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "暂存采购订单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.util.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  newPurchaseOrderWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作4",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newPurchaseOrderWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });
        
        //暂时保存按钮
        var closeButton = new Ext.Button({
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            newPurchaseOrderWin.destroy();
          }
        });
        
        //采购申请的FormPanel
        var purchaseOrderFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'new_purchase_order',
          labelWidth: 65,
          width: 1243,
          labelAlign: 'right',
          frame : true,
          url: '/purchase_order/create',
          method: 'GET',
          items: [{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [vendor]
                }, {
                  columnWidth: .25,
                  layout: 'form',
                  border: false,
                  items: [actionDate]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [contractNumber]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [taxRate]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [linkman]
                },{
                  columnWidth: .25,
                  layout: 'form',
                  border: false,
                  items: [phone]
                },{
                  columnWidth: .55,
                  layout: 'form',
                  border: false,
                  items: [deliveryAddress]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [desc]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [purchaseOrderDetailGrid]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 0.25,
                  layout: 'form',
                  border: false,
                  items: [sumAmount]
                },{
                  columnWidth: 0.25,
                  layout: 'form',
                  border: false,
                  items: [sumVATAmount]
                },{
                  columnWidth: 0.25,
                  layout: 'form',
                  border: false,
                  items: [sumTaxAmount]
                }]
            },temporary],
          buttons: [submitButton,tempSaveButton,closeButton]
        });
        purchaseOrderFormPanel.render('new_purchase_order');
        //
        purchaseOrderDetailGrid.on('afteredit', afterEdit, this );

        function afterEdit(obj) {
          
          if(obj.field=="product_name"||obj.field=="quantity"||obj.field=="tax_price"){
            if (obj.record.get('quantity') > obj.record.get('balance_quantity')){
              obj.record.set('quantity',obj.record.get('balance_quantity'));
            }
            if(obj.record.get('quantity')>0){
              //设置含税单价和含税竞价
              obj.record.set('unit_price',Math.round(10000000000*obj.record.get('tax_price')/(1+taxRate.getValue()*0.01))/10000000000);
              obj.record.set('tax_amount',obj.record.get('tax_price')*obj.record.get('quantity'));              
              obj.record.set('amount',Math.round(obj.record.get('quantity')*100*obj.record.get('unit_price'))/100);
              obj.record.set('value_added_tax',Math.round(obj.record.get('amount')*taxRate.getValue()*0.01*1000)/1000);
            }else{
              obj.record.set('amount',0);
            }
          }
          getSumAmount();
        }
        
        function getSumAmount(){
          sumAmount.setValue(0);
          sumVATAmount.setValue(0);
          sumTaxAmount.setValue(0);
          var records = purchaseOrderDetailDS.getRange(0,purchaseOrderDetailDS.getCount());
          for(var i = 0; i< records.length ;i++){
            var record = records[i];
            var quantity = record.get('quantity');
            var unitPrice = record.get('unit_price');
            var taxPrice = record.get('tax_price');
            //record.set('amount',quantity*unitPrice);
            //record.set('tax_amount',quantity*taxPrice);
            //var amount = record.get('amount');
            sumAmount.setValue(sumAmount.getValue()+record.get('amount'));
            sumVATAmount.setValue(sumVATAmount.getValue()+record.get('value_added_tax'));
            sumTaxAmount.setValue(sumTaxAmount.getValue()+record.get('tax_amount'));
          }
        }
      })
    </script>
  </head>
  <body>
    <div id="new_purchase_order"></div>
  </body>
</html>